'use strict';
var fs = require("fs");
var sqlite3 = require("sqlite3");
var path = require('path');
var config = require('./conf/config');
var sqlHelper= require('./sqlite3help');
var readline = require('readline'); 
var fileKit= require('./file-kit');
var crypto = require('crypto');
var EventProxy = require('eventproxy');
function checkFile(fullPath,ep){
	var start = new Date().getTime();
	var md5sum = crypto.createHash('md5');
	var sha1sum = crypto.createHash('sha1');
	var stream = fs.createReadStream(fullPath);
	stream.on('data', function(chunk) {
		md5sum.update(chunk);
		sha1sum.update(chunk);
	});
	stream.on('end', function() {
		var md5Value= md5sum.digest('hex').toUpperCase();
		var sha1Value= sha1sum.digest('hex').toUpperCase();
		//console.log('文件:'+path+',MD5签名为:'+md5Value+'.耗时:'+(new Date().getTime()-start)/1000.00+"秒");
		ep.emit('md5',md5Value);
		ep.emit('sha1',sha1Value);
	});
}

function walkDir(out,dirPath,rootKey,callback){
  dirPath=path.normalize(dirPath);
	//console.log("search: "+dirPath);
  fs.readdir(dirPath, function(err, entries){
	if(!entries){ return;}
	entries.forEach(function(ent){
	 var fullPath = path.join(dirPath, ent);
	 (function(fullPath){
		 var stats=fs.statSync(fullPath, function (err, stats){});
		 if(stats){
		   var result= fileKit.getResult(stats,fullPath,rootKey,config.filePath[rootKey]); 
		   if(stats.isDirectory()){
			 out.write(JSON.stringify(result)+"\r\n");
			 setTimeout(function() {  
			   walkDir(out,fullPath,rootKey,callback);
			 }, 500);  
		   }else if(stats.isFile()){
		    var ep = new EventProxy();
			checkFile(fullPath,ep);
			ep.all('md5', 'sha1', function (md5Value, sha1Value) {
				result.file_md5=md5Value;
				result.file_sha1=sha1Value;
				//callback();
				out.write(JSON.stringify(result)+"\r\n");
			});
		   }
		 }
	 })(fullPath);
	});
  });
}
var filePaths=config.filePath;
var count=0;
if(filePaths){
	for(var key in filePaths) {
		var initFile="./data/"+key+".json";
		var out = fs.createWriteStream(initFile);
		walkDir(out,config.filePath[key],key,function(){
			console.log('处理完成!'); 
		});
		count++;
		out.on('close', function() {
			console.log('处理完成!');         
		})
	}
	
}


